package com.ifcar.app.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.ifcar.app.util.Logger;



/**
 * 文件上传类
 * @author ThinkPad
 *
 */
public class Upload extends Base {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6786031569958173042L;


	public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
			
			HttpServletRequest req = (HttpServletRequest) request;
			HttpServletResponse resp = (HttpServletResponse) response;
			req.setCharacterEncoding("UTF-8");
			String content = "";
			String method = req.getParameter("method");
			
			if ("avatar".equals(method)) {
				content = avatar(req,resp);
				sendContent(resp, content, CONTEXT_TYPE);
			}else{
				_404Content(resp);
			}
	}
	
	/*
	 * 用户上传头像
	 */
	public String avatar(HttpServletRequest request, HttpServletResponse response){
		
		
		DiskFileItemFactory factory = new DiskFileItemFactory();	
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		
		Logger.log("avatar");
		Logger.log(""+upload.isMultipartContent(request));
		if(!upload.isMultipartContent(request)){
			return "{\"stus\":false}";
		}else{
			
			try {
				
				List list = upload.parseRequest(request);
				Iterator it=list.iterator();
				
				while(it.hasNext())
				{
					FileItem item=(FileItem)it.next();
					String filename = item.getName();
					String path=this.getServletContext().getRealPath("/upload/");
					
					FileOutputStream out=new FileOutputStream(path+filename);
					InputStream in = item.getInputStream();
					byte buffer[] = new byte[1024];
					int len = 0;
					
					while((len=in.read(buffer))>0){
						
						out.write(buffer,0,len);
					 
					}
					
					in.close();
					out.close();
				}
				
			} catch (Exception e) {
				return "{\"stus\":"+e.toString()+"}";
			}
			
			return "{\"stus\":true}";
		}
		
	}
	
}
